import axios from 'axios';
import { message } from 'antd'
import { createHashHistory } from 'history'
const history = createHashHistory()

//而之所以要创建axios实例，是因为我们实际工作项目中，可能需要访问多个服务地址，
//而这些服务请求和响应的结构也可能都完全不同，那么你可以通过axios.create创建不同的实例来处理。
const instance = axios.create({ //axios.create()创建一个新的axios实例
    baseURL: window.BASEURL,
    timeout: 500000,
    headers: { 'X-Custom-Header': 'foobar', 'Content-Type': 'application/json' },
    //添加 contentType：“application/json“之后，向后台发送数据的格式必须为json字符串
    //responseType: 'json',
});
instance.interceptors.request.use(async config => {   
    if(config.url == "/system/0/media/play"){
        config.baseURL = window.MEDIAPLAYURL;
    }else{
        config.baseURL = window.BASEURL;
    }
    const token = sessionStorage.getItem('token') 
    if (token) {
        let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        config.headers.authorization = token;
        config.headers["X-UID"] = userInfo.id;
    }
    config.headers['TENANT-ID']= sessionStorage.getItem('TENANT-ID');
    //config.headers['DATA-NODE']= sessionStorage.getItem('DATA-NODE');   
    return config

}, error => {
    return Promise.reject(error);
});

instance.interceptors.response.use(({ data,config }) => {
    if (data.status === '100') {
        sessionStorage.removeItem('token');
        history.replace('/login')
    } else if(!config.useMineErrMsg){ //使用公用默认提示
        if (data.status && data.status !== '0') {
            message.error(data.message);
        } else if (!!data.state && data.state != "SUCCESS") {
            message.error(data.message);
        }
    }
    return data;
}, error => {
    let text = JSON.parse(JSON.stringify(error)).response.status === 404
        ? '404'
        : '网络异常，请重试';
    message.error(text);
    return Promise.reject({ status: -1, message: text });
});

const request = {
    appid: async (url, config) => {
        return instance.get(url, config)
            .then((data) => {
                if (data) {
                    return data;
                }
            })
            .catch(error => {
                return error;
            });

    },
    post: async (url, param,config) => {
        param = param || {};
        return instance.post(url, param,config)
            .then((data) => {
                if (data) {
                    return data;
                }
            })
            .catch(error => {
                return error;
            });
    },
    delete: async (url, param,config) => {
        param = param || {};
        return instance.delete(url, param,config)
            .then((data) => {
                if (data) {
                    return data;
                }
            })
            .catch(error => {
                return error;
            });
    },
};
export default request;


